package org.mozhu.zufang.wechat.wx.oauth;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mozhu.zufang.wechat.wx.WechatConstants;
import org.mozhu.zufang.wechat.wx.WechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class OAuthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    WechatService wechatService;

    @SuppressWarnings("rawtypes")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String openId = (String) request.getSession().getAttribute(WechatConstants.OPEN_ID);
        String requestUri = request.getServletPath();
        if (requestUri.startsWith("/wechat/assets")) {
            return true;
        }
        log.debug("Get OpenId[{}] in Session, request uri[{}]", openId, requestUri);
        if (StringUtils.isNotBlank(openId) || !"GET".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        openId = System.getProperty(WechatConstants.DEBUG_OPEN_ID);
        if (StringUtils.isNotBlank(openId)) {
            request.getSession().setAttribute(WechatConstants.OPEN_ID, openId);
            return true;
        }

        if (isOAuthRequired(handler)) {
            String code = request.getParameter("code");
            String fetchUserInfo = request.getParameter("fetch_userinfo");
            log.debug("code=[${code}], fetch_userinfo=[${fetchUserInfo}]");
            if (code == null) {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Cache-Control", "no-store");
                response.setDateHeader("Expires", 0);
                response.setHeader("Pragma", "no-cache");
                String redirectUrl = buildRedirectUrl(request);
                log.debug("Set oauth success redirectUrl to [{}]", redirectUrl);
                if ("true".equalsIgnoreCase(fetchUserInfo)) {
                    String url = wechatService.getUrlForProfile(redirectUrl);
                    log.debug("Redirect to url [{}]", url);
                    response.sendRedirect(url);
                } else {
                    String url = wechatService.getUrlForCode(redirectUrl);
                    log.debug("Redirect to url [{}]", url);
                    response.sendRedirect(url);
                }
                return false;
            } else {
                if ("true".equalsIgnoreCase(fetchUserInfo)) {
                    OAuthUserInfo userInfo = wechatService.getUserInfo(code);
                    openId = userInfo.getOpenId();
                    request.getSession().setAttribute(WechatConstants.USER_INFO, userInfo);
                } else {
                    log.debug("Try to get openId by code[{}] from wechat server", code);
                    openId = wechatService.getOpenId(code);
                }
                log.debug("Set openId[{}] to session", openId);
                request.getSession().setAttribute(WechatConstants.OPEN_ID, openId);
                return true;
            }
        }
        return true;
    }

    private boolean isOAuthRequired(Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        OAuthRequired annotation = handlerMethod.getMethodAnnotation(OAuthRequired.class);
        if (annotation != null) {
            return annotation.value();
        }

        OAuthRequired[] annotations = handlerMethod.getBeanType().getAnnotationsByType(OAuthRequired.class);
        if (annotations != null && annotations.length > 0) {
            return annotations[0].value();
        }

        annotations = handlerMethod.getBeanType().getSuperclass().getAnnotationsByType(OAuthRequired.class);
        if (annotations != null && annotations.length > 0) {
            return annotations[0].value();
        }

        return false;
    }

    private String buildRedirectUrl(HttpServletRequest request) {
        String url = request.getRequestURL().toString();
        String param = request.getQueryString();
        if (param != null && param.length() > 0) {
            url = url + "?" + param;
        }
        return url;
    }
}
